<template>
  <div>
    <div v-if="props.type == 'mileage'" class="col-text" :class="getMileageStatus(props.record).color">
      {{ getMileageStatus(props.record).text }}</div
    >
    <div v-else class="col-text" :class="getFormattedDateDiff(props.date).color"> {{ getFormattedDateDiff(props.date).text }}</div>
  </div>
</template>

<script setup lang="ts">
  import { watch, ref } from 'vue'
  import dayjs from 'dayjs'
  import { isValid } from '@/utils'

  const props = defineProps({
    date: {
      type: String,
      default: '',
    },
    record: {
      type: Object,
      default: '',
    },
    type: {
      type: String,
      default: '',
    },
    value: {
      type: String,
      default: 'estimatedKilometre'
    }
  })
  // 假设 newValue 是数据中的到期日期
  const getFormattedDateDiff = (newValue) => {
    if (!newValue) {
      return '-'
    }
    const today = dayjs().startOf('day') // 获取当前日期，忽略时分秒
    const endDate = dayjs(newValue).startOf('day') // 转换到期日期，忽略时分秒
    const diffDays = endDate.diff(today, 'day') // 计算天数差
    if (diffDays >= 0) {
      return {
        text: `剩余 ${diffDays} 天`, // 剩余天数
        color: 'green', // 绿色
      }
    } else {
      return {
        text: `已超 ${Math.abs(diffDays)} 天`, // 已超天数
        color: 'red', // 红色
      }
    }
  }
  const getMileageStatus = (record) => {
    if (!isValid(record[props.value])) {
      return ''
    }
    let totalMileage = record.totalMileage ? record.totalMileage : 0
    const mileageDiff = record[props.value] - totalMileage // 计算差距

    if (mileageDiff >= 0) {
      return {
        text: `剩余 ${mileageDiff} 公里`, // 剩余公里数
        color: 'green', // 绿色
      }
    } else if (mileageDiff < 0) {
      return {
        text: `已超 ${Math.abs(mileageDiff)} 公里`, // 已超公里数
        color: 'red', // 红色
      }
    } else {
      return '-'
    }
  }
</script>

<style lang="less" scoped>
  .col-text {
    font-size: 13px;
  }
  .green {
    color: #00b42a;
  }
  .red {
    color: #f76965;
  }
</style>
